import json
from bson import ObjectId
from datetime import datetime, date


class JsonCustomEncoder(json.JSONEncoder):
    """
    用于解决 ObjectId datetime date 等类型的 json 导出问题
    使用方式：json.dumps(data, cls = JsonCustomEncoder)
    """
    def default(self, field):
        if isinstance(field, ObjectId):
            return str(field)
        elif isinstance(field, datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, date):
            return field.strftime('%Y-%m-%d')
        elif isinstance(field, bytes):
            return "not supported"
        else:
            return json.JSONEncoder.default(self, field)